#pragma once

#include <iostream>
#include <string>
#include <strings.h>
#include <unordered_map>
using namespace std;

/*网络必要头文件*/
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

/*用户具有的属性*/
class Users
{
public:
    Users(const string &ip, const uint16_t &port)
        : _ip(ip), _port(port)
    {}

public:
    string _ip;
    uint16_t _port;
};

/*管理用户的类*/
class onlineUsers
{
public:
    /*添加用户，即将ip+port作为key，Users对象作为value*/
    void addUser(const string &ip, const uint16_t &port)
    {
        string id = ip + to_string(port);
        _users.insert(make_pair(id, Users(ip, port)));
    }

    /*删除用户，通过id作为key删除用户*/
    void delUser(const string &ip, const uint16_t &port)
    {
        string id = ip + to_string(port);
        _users.erase(id);
    }

    /*判断是否在线*/
    bool isOnline(const string &ip, const uint16_t &port)
    {
        string id = ip + to_string(port);
        return _users.find(id) == _users.end() ? false : true;
    }

    /*向在线的所有用户转发消息*/
    void routingMessage(int _socketFd,const string &ip,const uint16_t &port,string &message)
    {
        for(auto &user : _users)
        {
            struct sockaddr_in client;
            bzero((void *)&client,sizeof(client));
            client.sin_family = AF_INET;
            client.sin_port = htons(user.second._port);
            client.sin_addr.s_addr = inet_addr(user.second._ip.c_str());
            
            string s = ip + "-" + to_string(port) + "# " + message;
            sendto(_socketFd,s.c_str(),s.size(),0,(struct sockaddr *)&client,sizeof(client));
        }
    }

private:
    /*哈希表存储用户*/
    unordered_map<string, Users> _users;
};